﻿<#
    Script  : ImportPSModule
    Author  : Riwut Libinuko
    Blog    : http://blog.libinuko.com 
    Copyright :© IdeasFree - cakriwut@gmail.com, 2013. All rights reserved.
#>

function Import-PSModule-List
{
  param(
	  [Parameter(ParameterSetName="List")]
      [string] $source= $globalPkgSource,
	  [Parameter(ParameterSetName="List")]
      [string] $tags='PSModule',
	  [Parameter(ParameterSetName="List")]
	  [switch] $ListAvailable
   )
   
   #Get feed url
   $serviceBase = GetPackageUrl $source
   $feedUrl = $serviceBase + "Packages"
   $feedUrl = $feedUrl +"?`$filter=(IsLatestVersion eq true) and substringof(`'$tags`',Tags)"
   	
   do {
     $feed = [xml]$webClient.DownloadString($feedUrl) 
     $entries = $feed | select -ExpandProperty feed | select -ExpandProperty entry -ErrorAction SilentlyContinue  
               	
     if($entries)
     {
       $entries |% {      
         if($_.properties.id)
         {  
           $packageName = $_.properties.id   		 
         } else {
           $packageName = $_.title."#text" 
         }
		 $pkgLocation = if($packageName -eq "ImportPSModule") { Join-Path $globalPkgInstallationDir "..\..\" }
		                else { join-path $globalPkgInstallationDir $packageName }
		         
		 if(($pkgInfo = GetPackageInfo $pkgLocation) -ne $null)
		 {
		    $versionStatus = CompareVersion $pkgInfo.Version $_.properties.version
			$installedVersion = $pkgInfo.Version
			if($versionStatus -lt 0)
			{
			  $status = "Need upgrade"
			} elseif($versionStatus -gt 0)
			{
			   $status = "Newer"
			} else {
			   $status = "Installed"
			}
		 } else {
		    $status = "Not Installed"
			$installedVersion = $null
		 }
		 
		 New-Object PSObject -Property @{
           Name=$packageName;
		   Version=$_.properties.version;
		   InstalledVersion = $installedVersion
		   Status= $status;        
	     } | select Name,Version,InstalledVersion,Status
	  }
	   
	   if(($link = $feed.feed.link | where { $_.rel.startsWith("next") } | select href ) -ne $null)
	   {
	      $feedUrl = $link.href
	   } 
	 } else {
	   Write-Host "Can not find any packages."
	   $link = $null
       return $null
	 }
	}
    while($link -ne $null)
}
